package com.demo.util.equals.utils;

import com.demo.util.equals.beans.EqualsRangeVO;
import com.demo.util.equals.functional.Equals;
import com.demo.util.CollUtil;

import java.util.ArrayList;
import java.util.List;

public class EqualsUtil {

    public static <T> List<EqualsRangeVO> getEqualsRange(List<T> list, Equals<T> equalsFunc) {
        List<EqualsRangeVO> result = new ArrayList<>();
        if (CollUtil.isEmpty(list)) {
            return result;
        }
        Integer saveIndex = null;
        int length = list.size();
        for (int index = 1; index < length; index++) {
            int lastIndex = index - 1;
            T last = list.get(lastIndex);
            T that = list.get(index);
            boolean equals = equalsFunc.equals(last, that);
            boolean isEnd = index == length - 1;
            if (equals && saveIndex == null) {
                saveIndex = lastIndex;
            }
            if ((!equals || isEnd) && saveIndex != null) {
                int size = (equals ? index : lastIndex) - saveIndex;
                result.add(new EqualsRangeVO(saveIndex, size));
                saveIndex = null;
            }
        }
        return result;
    }

}
